import React from "react";
import {connect} from "react-redux";
import {setUserInfo} from "../redux/user.redux";
import { setToken,setLocationToken } from "@/axios/auth";
import { Form, Input, Button,message, Checkbox,Row, Col} from "antd";
import "./css/Login.css"

import {login} from "@/api/login"

const Item=Form.Item;


@connect(
  null,
  {setUserInfo}
)
class Login extends React.Component{
  constructor(props) {
    super(props);

    this.state={
      loginForm:{
        username:"",
        password:"",
        remember:false,
        rules:{
          username: [
            {
              required: true,
              message: 'Please input your username!',
            },
          ],
          password: [
            {
              required: true,
              message: 'Please input your password!',
            },
          ]
        }
      }
    }
    this.onFinish=this.onFinish.bind(this);
    this.onFinishFailed=this.onFinishFailed.bind(this);

  }

  onFinish(values){
    console.log('Success:', values);
    let {username,password,remember}=values;
    login({username,password}).then(res=>{
      if(res["code"]==="0"){
        let {token,info}=res;
        let userInfo={user:info.user
          ,dynamicRoutes:info.dynamicRoutes
          ,token};
        message.success(res["message"])
        this.props.setUserInfo(userInfo);
        setToken(token);
        if(remember){
          setLocationToken(token);
        }
        this.props.history.push('/');
      }else{
        message.error(res["message"])
      }
    }).catch(err=>{
      message.error("后台报错，请联系管理员")
    })
    // this.props.setUserName("user");
  }
  onFinishFailed(errorInfo ){
    console.log('Failed:', errorInfo);
  }
  render() {
    const layout = {
      labelCol: {
        span: 8,
      }
    };
    const tailLayout = {
      wrapperCol: {
        offset: 8,
        span: 16,
      },
    };
    return (
      <div className="login-div">
        <Row>
          <Col span={8} offset={8}>
            <Form {...layout}
                  onFinish={this.onFinish}
                  onFinishFailed={this.onFinishFailed}>
              <Item
                label="Username"
                name="username"
                rules={this.state.loginForm.rules.username}
              >
                <Input />
              </Item>
              <Item
                label="Password"
                name="password"
                rules={this.state.loginForm.rules.password}
              >
                <Input.Password />
              </Item>
              <Item {...tailLayout} name="remember" valuePropName="checked">
                <Checkbox>Remember me</Checkbox>
              </Item>
              <Item  {...tailLayout} >
                <Button type="primary" htmlType="submit">
                  Submit
                </Button>
              </Item>
            </Form>
          </Col>
        </Row>
      </div>
    );
  }
}

export default Login;
